package com.ls.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ls.config.satoken.SaTokenUtilPy;
import com.ls.controller.holidaycategory.model.AddCategoryModel;
import com.ls.controller.holidaycategory.model.CategoryStatusVo;
import com.ls.controller.holidaycategory.model.EditCategoryModel;
import com.ls.controller.holidaycategory.model.GetCategoryModel;
import com.ls.entity.*;
import com.ls.enums.RoleEnum;
import com.ls.mapper.HolidayCategoryMapper;
import com.ls.service.*;
import com.ls.utils.ResultData;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.ls.constant.SystemConstants.*;

/**
 * <p>
 * 节假日分类 服务实现类
 * </p>
 *
 * @author pengyu
 * @since 2024-10-12
 */
@Service
@Slf4j
public class HolidayCategoryServiceImpl extends ServiceImpl<HolidayCategoryMapper, HolidayCategory> implements IHolidayCategoryService {
    @Lazy
    private final ICustomerService customerService;
    @Lazy
    private final IHolidayService holidayService;
    @Lazy
    private final IRuleTemplateService ruleTemplateService;
    @Lazy
    private final IRuleLinkmanService ruleLinkmanService;
    @Lazy
    private final ISmsRuleService smsRuleService;
    @Lazy
    private final ISmsTemplateService smsTemplateService;
    @Autowired
    public HolidayCategoryServiceImpl(@Lazy ICustomerService customerService,
                                      @Lazy IHolidayService holidayService,
                                      @Lazy IRuleTemplateService ruleTemplateService,
                                      @Lazy IRuleLinkmanService ruleLinkmanService,
                                      @Lazy ISmsRuleService smsRuleService,
                                      @Lazy ISmsTemplateService smsTemplateService
    ) {
        this.customerService = customerService;
        this.holidayService = holidayService;
        this.ruleTemplateService = ruleTemplateService;
        this.ruleLinkmanService = ruleLinkmanService;
        this.smsRuleService = smsRuleService;
        this.smsTemplateService = smsTemplateService;
    }

    /**
     * 新增节假日分类
     */
    @Override
    public ResultData add(AddCategoryModel model) {
        Customer customer = SaTokenUtilPy.getCustomer();
        //判断当前用户是否存在重复的分类
        HolidayCategory holidayCategory1 = getOne(new LambdaQueryWrapper<HolidayCategory>()
                .eq(HolidayCategory::getCustomerId, customer.getCustomerId())
                .eq(HolidayCategory::getValidFlag, VALID_TRUE)
                .eq(HolidayCategory::getCategoryName, model.getCategoryName()));
        if (holidayCategory1 != null) {
            return ResultData.failure("当前用户已存在该分类！");
        }
        HolidayCategory holidayCategory = new HolidayCategory();
        BeanUtils.copyProperties(model, holidayCategory);
        holidayCategory.setCustomerId(customer.getCustomerId());
        holidayCategory.setCategoryType(HOLIDAY_CATEGORY_TYPE_USER);
        holidayCategory.setCreateTime(LocalDateTime.now());
        holidayCategory.setUpdateTime(LocalDateTime.now());
        holidayCategory.setValidFlag(VALID_TRUE);
        Boolean flag = saveOrUpdate(holidayCategory);
        if (flag) {
            return ResultData.successMsg("新增成功");
        } else {
            return ResultData.failure("新增失败");
        }
    }

    /**
     * 更新节假日分类
     */
    @Override
    public ResultData edit(EditCategoryModel model) {
        Customer customer = SaTokenUtilPy.getCustomer();
        //判断当前用户是否存在重复的分类
        HolidayCategory holidayCategory1 = getOne(new LambdaQueryWrapper<HolidayCategory>()
                .eq(HolidayCategory::getCustomerId, customer.getCustomerId())
                .eq(HolidayCategory::getValidFlag, VALID_TRUE)
                .eq(HolidayCategory::getCategoryName, model.getCategoryName())
                .ne(HolidayCategory::getCategoryId, model.getCategoryId()));
        if (holidayCategory1 != null) {
            return ResultData.failure("当前用户已存在该分类！");
        }
        HolidayCategory holidayCategory = getById(model.getCategoryId());
        BeanUtils.copyProperties(model, holidayCategory);
        holidayCategory.setUpdateTime(LocalDateTime.now());
        Boolean flag = saveOrUpdate(holidayCategory);
        if (flag) {
            return ResultData.successMsg("更新成功");
        } else {
            return ResultData.failure("更新失败");
        }
    }
    /** 查询节假日分类能否删除 */
    @Override
    public ResultData getCategoryStatus(Long categoryId) {
        CategoryStatusVo categoryStatusVo = new CategoryStatusVo();
        HolidayCategory holidayCategory = getById(categoryId);
        if (holidayCategory.getCategoryType()==NUMBER_0){
            categoryStatusVo.setStatus(false);
            categoryStatusVo.setMessage("系统分类不能删除");
        }else {
            List<Long> holidayIds=new ArrayList<>();
            List<Holiday> holidays = holidayService.list(new LambdaQueryWrapper<Holiday>()
                    .eq(Holiday::getCategoryId, categoryId)
                    .eq(Holiday::getValidFlag, VALID_TRUE));
            if (holidays.size()>0){
//                holidayIds= Optional.ofNullable(holidays)
//                        .orElse(Collections.emptyList())
//                        .stream()
//                        .map(Holiday::getHolidayId)
//                        .collect(Collectors.toList());
//                List<SmsRule> smsRules = smsRuleService.list(new LambdaQueryWrapper<SmsRule>()
//                        .in(SmsRule::getHolidayId, holidayIds)
//                        .eq(SmsRule::getValidFlag, VALID_TRUE));
//                if (smsRules.size()>0){
//                    categoryStatusVo.setStatus(false);
//                    categoryStatusVo.setMessage("该分类下有正在执行中的关怀/提醒事件，不可删除。");
//                }else {
//                    categoryStatusVo.setStatus(true);
//                    categoryStatusVo.setMessage("删除该分类的同时，会删除分类下的所有自定义纪念日，绑定的模板和绑定的规则");
//                    categoryStatusVo.setHolidayIds(holidayIds);
//                }
                categoryStatusVo.setStatus(false);
                categoryStatusVo.setMessage("该分类存在节日，不可删除。");
            }else {
                categoryStatusVo.setStatus(true);
            }
        }
        return ResultData.successData(categoryStatusVo);
    }
    /**
     * 删除节假日分类
     */
    @Override
    public ResultData del(Long categoryId) {
        ResultData resultData1=getCategoryStatus(categoryId);
        CategoryStatusVo categoryStatusVo = (CategoryStatusVo) resultData1.getData();
        if (!categoryStatusVo.getStatus()){
            return ResultData.failure(categoryStatusVo.getMessage());
        }
        log.info("删除分类：{}",categoryStatusVo.getHolidayIds());
        if (categoryStatusVo.getHolidayIds()!=null&&categoryStatusVo.getHolidayIds().size()>0){
            return ResultData.failure("请先删除分类下的所有纪念日");
//            //移除绑定的节日
//            categoryStatusVo.getHolidayIds().forEach(holidayId -> {
//                Holiday holiday=holidayService.getById(holidayId);
//                holiday.setValidFlag(VALID_FALSE);
//                holidayService.saveOrUpdate(holiday);
//            });
//            //移除模板和规则
//            smsTemplateService.remove(new LambdaQueryWrapper<SmsTemplate>()
//                    .in(SmsTemplate::getHolidayId, categoryStatusVo.getHolidayIds())
//            );
//            List<Long> ruleIds=smsRuleService.list(new LambdaQueryWrapper<SmsRule>()
//                    .in(SmsRule::getHolidayId, categoryStatusVo.getHolidayIds())
//                    .eq(SmsRule::getValidFlag, VALID_FALSE)
//            ).stream()
//                    .map(SmsRule::getRuleId)
//                    .collect(Collectors.toList());
//            //删除绑定的规则
//            smsRuleService.remove(new LambdaQueryWrapper<SmsRule>().in(SmsRule::getRuleId, ruleIds));
//            //删除模板和规则的绑定的联系人
//            ruleTemplateService.remove(new LambdaQueryWrapper<RuleTemplate>().in(RuleTemplate::getRuleId, ruleIds));
//            ruleLinkmanService.remove(new LambdaQueryWrapper<RuleLinkman>().in(RuleLinkman::getRuleId, ruleIds));
        }
        HolidayCategory holidayCategory = getById(categoryId);
        holidayCategory.setUpdateTime(LocalDateTime.now());
        holidayCategory.setValidFlag(VALID_FALSE);
        Boolean flag = saveOrUpdate(holidayCategory);
        if (flag) {
            return ResultData.successMsg("删除成功");
        } else {
            return ResultData.failure("删除失败");
        }
    }

    /**
     * 查询节假日分类
     */
    @Override
    public ResultData getCategory(GetCategoryModel model) {
        LambdaQueryWrapper<HolidayCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(model.getCategoryType()!=null,HolidayCategory::getCategoryType, model.getCategoryType())
                .eq(HolidayCategory::getValidFlag, VALID_TRUE)
                .orderByAsc(HolidayCategory::getCreateTime);

        // 修正条件构造逻辑
        if (model.getCustomerId() != null){
            if (model.getCustomerId() == 0){
                wrapper.eq(HolidayCategory::getCustomerId, 0);
            }else {
                // 使用嵌套条件构造器
                wrapper.nested(q -> q.eq(HolidayCategory::getCustomerId, model.getCustomerId())
                        .or()
                        .eq(HolidayCategory::getCustomerId, 0));
            }
        }
        List<HolidayCategory> holidayCategoryList = list(wrapper);
        holidayCategoryList.forEach(holidayCategory -> {
            String phone=null;
            if (holidayCategory.getCustomerId() != 0){
                // 添加空值检查
                Customer customer = customerService.getById(holidayCategory.getCustomerId());
                phone = Optional.ofNullable(customer)
                        .map(Customer::getPhone)
                        .orElse(null);
            }
            holidayCategory.setPhone(phone);
        });
        return ResultData.successData(holidayCategoryList);
    }
    /**
     * 查询节假日分类
     */
    @Override
    public ResultData getCategoryApp(GetCategoryModel model) {
        LambdaQueryWrapper<HolidayCategory> wrapper = new LambdaQueryWrapper<>();
        Long customerId = model.getCustomerId() != null ? model.getCustomerId()
                : SaTokenUtilPy.getCustomer().getCustomerId();

        wrapper.eq(model.getCategoryType()!=null,HolidayCategory::getCategoryType, model.getCategoryType())
                .eq(HolidayCategory::getValidFlag, VALID_TRUE)
                .orderByAsc(HolidayCategory::getCreateTime);

        // 修正条件构造逻辑
        if (customerId == 0) {
            wrapper.eq(HolidayCategory::getCustomerId, 0);
        } else {
            // 使用嵌套条件构造器
            wrapper.nested(q -> q.eq(HolidayCategory::getCustomerId, customerId)
                    .or()
                    .eq(HolidayCategory::getCustomerId, 0));
        }

        List<HolidayCategory> holidayCategoryList = list(wrapper);
        holidayCategoryList.forEach(holidayCategory -> {
            String phone=null;
            if (holidayCategory.getCustomerId() != 0){
                phone=customerService.getById(holidayCategory.getCustomerId()).getPhone();
            }
            holidayCategory.setPhone(phone);
        });
        return ResultData.successData(holidayCategoryList);
    }

    /**
     * 获取分类详情
     */
    @Override
    public ResultData getCategoryDetail(Long categoryId) {
        if (categoryId == null) {
            return ResultData.failure("分类ID不能为空");
        }

        HolidayCategory holidayCategory = getOne(new LambdaQueryWrapper<HolidayCategory>()
                .eq(HolidayCategory::getCategoryId, categoryId)
                .eq(HolidayCategory::getValidFlag, VALID_TRUE));

        if (holidayCategory == null) {
            return ResultData.failure("分类不存在");
        }

        // 设置创建者手机号信息
        if (holidayCategory.getCustomerId() != 0) {
            Customer customer = customerService.getById(holidayCategory.getCustomerId());
            String phone = Optional.ofNullable(customer)
                    .map(Customer::getPhone)
                    .orElse(null);
            holidayCategory.setPhone(phone);
        }

        return ResultData.successData(holidayCategory);
    }
}
